/**
 * 生成随机名称
 */
export function getRandomName(len) {
  len = len || 6;
  const chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
  const maxPos = chars.length;
  let rand = "";
  for (let i = 0; i < len; i++) {
    rand += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return `${Math.floor(Date.now() / 1000)}${rand}`;
}
/**
 * 获取六位随机数
 */
export function getRandomFourDigitNumber() {
  const randomNum1 = Math.floor(Math.random() * 90) + 10;
  const randomNum2 = Math.floor(Math.random() * 90) + 10;
  const randomNum3 = Math.floor(Math.random() * 90) + 10;
  const randomNum = randomNum1 + "" + randomNum2 + "" + randomNum3;
  return Number(randomNum);
}
/**
 * 格式化时间
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}
/**
 * 数组去重
 * @param {Array} arr
 * @returns {Array}
 */
export function arrayDeduplication(arr) {
  const newArr = arr.filter(function (item, index, self) {
    return self.indexOf(item) === index;
  });
  return newArr;
}
/**
 * 获取链接参数
 */
export function queryURLParams(key) {
  const parames = {};
  const url = window.location.href;
  const pattern = /(\w+)=(\w+)/gi; //定义正则表达式
  url.replace(pattern, ($, $1, $2) => {
    parames[$1] = $2;
  });
  for (const i in parames) {
    if (i == key) {
      return parames[i];
    }
  }
  return null;
}
